<?php

namespace app\controller;

use app\BaseController;
use app\model\Sales;
use app\services\SalesListService;
use app\utils\CharacterUtils;
use app\utils\ExcelUtils;
use app\validate\SalesValidate;
use think\App;
use think\facade\Cache;

class SalesListController extends BaseController
{

    /**
     * @var Sales
     */
    private $dao;

    public function __construct(App $app)
    {
        $this->dao = new Sales();
        parent::__construct($app);
    }

    public function save2db(){
        $uploadedFile = $this->request->file('excel');

        $excelUtils = new ExcelUtils();
        $salesList = $excelUtils->excel2arr('Sales', $uploadedFile);


        $result = [];
        foreach ($salesList as $salesArr){

            if (!preg_match('/\d+/', $salesArr[0])) continue;
            $result[] = $this->dao->create([
                'staff_id'=> $salesArr[0],
                'name'=> $salesArr[1],
                'hk_mobile'=> $salesArr[2],
                'mac_mobile'=> $salesArr[3],
                'email'=> $salesArr[4],
                'property'=> $salesArr[5],
                'team'=> $salesArr[6],
                'squads'=> $salesArr[7],
                'staff_property'=> $salesArr[8],
                'department'=> $salesArr[9]
            ]);


        }
        return $this->returnJson($result);
    }

    public function getSalesListFormRedis(){
        $id = $this->request->param('id', '08155');

        $salesListService = new SalesListService();
        $salesList = $salesListService->getSalesFromRedis($id);


        return $this->returnJson($salesList);
    }

    public function add(){
        $param = $this->request->param();
        Validate(SalesValidate::class)
            ->scene('add')
            ->check($param);

        return $this->returnJson($this->dao->create($param));
    }


    public function getList(){
        $keyword = $this->request->param('keyword');

        return $this->returnJson($this->dao->where('staff_id|name|hk_mobile|mac_mobile|email','like', '%'.$keyword.'%')->select());
    }

}